package com.tingyun.sign.questions.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tingyun.sign.activity.service.impl.ActivityServiceImpl;
import com.tingyun.sign.core.entity.ScActivityBean;
import com.tingyun.sign.core.entity.ScQuestionsBean;
import com.tingyun.sign.core.entity.ScUCompanyUserBean;
import com.tingyun.sign.core.repository.ActivityDao;
import com.tingyun.sign.core.repository.CompanyUserDao;
import com.tingyun.sign.core.repository.ScQuestionsDao;
import com.tingyun.sign.questions.service.QuestionsService;
import com.tingyun.sign.utils.DateUtils;
import com.tingyun.sign.utils.MyAssert;
import com.tingyun.sign.utils.Page;
@Service("questionsService")
public class QuestionsServiceImpl implements QuestionsService{
	
	private static Logger log = LoggerFactory.getLogger(ActivityServiceImpl.class);
	@PersistenceContext(name = "jpa")
	private EntityManager entityManager;
	@Autowired
	private ScQuestionsDao scQuesionsDao;
	@Autowired
	private ActivityDao activityDao;
	@Autowired
	private CompanyUserDao companyUserDao;
	
	/*
	 * 添加问题
	*/
	@Override
	public Integer addQuestions(ScQuestionsBean bean) {
		
		MyAssert.notNull(bean.getActivityId(), "活动id为空");
		MyAssert.notNull(bean.getCompanyUserId(), "提问者为空");
		MyAssert.notNull(bean.getContent(), "提问内容为空");
		try {
			bean.setCtime(new Date());
			bean.setMtime(new Date());
			scQuesionsDao.save(bean);
		} catch (Exception e) {
			log.error("问题添加失败", e);
			MyAssert.isTrue(false, "系统异常，添加问题失败，请稍后重试");
		}
		return 1;
	}

	//回复问题
	@Override
	@Transactional
	public Integer answerQuestion(ScQuestionsBean bean) {
		MyAssert.notNull(bean.getId(), "问题id为空");
		MyAssert.notNull(bean.getAnswer(), "输入答案为空");
		try {
			bean.setMtime(new Date());
			scQuesionsDao.updateAnswerById(bean.getId(),bean.getAnswer(),bean.getMtime(),bean.getMuser());
		} catch (Exception e) {
			log.error("答案输入失败", e);
			MyAssert.isTrue(false, "系统异常，添加问题失败，请稍后重试");
		}
		return 1;
	}
	
//	显示所有问题
	/**
	 * 根据活动ID查询问题列表,在提问页面下方显示
	 * 参数：活动id
	 */
/*	public Page<ScQuestionsBean> listQuestions(ScQuestionsBean bean) {
		//必填参数校验
		MyAssert.notNull(bean.getActivityId(), "参数[活动ID]为空");
		//分页查询
		Page<ScQuestionsBean> page = new Page<ScQuestionsBean>();
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<ScQuestionsBean> cq = cb.createQuery(ScQuestionsBean.class);
		Root<ScQuestionsBean>  root = cq.from(ScQuestionsBean.class);
		//整合查询条件
		List<Predicate> pres = new ArrayList<Predicate>();
		pres.add(cb.equal(root.get("activityId"), bean.getActivityId()));
		if(bean.getId()!=null) {
			pres.add(cb.equal(root.get("id"), bean.getId()));
		}
		Predicate p = cb.and(pres.toArray(new Predicate[pres.size()]));
		cq.where(p);//and
		cq.orderBy(cb.desc(root.get("id")));//排序
		//执行查询
		TypedQuery<ScQuestionsBean> query = entityManager.createQuery(cq);
//		query.setFirstResult(bean.getStart());
//		query.setMaxResults(bean.getPageSize());
		List<ScQuestionsBean> list = query.getResultList();
		page.setResultList(list);
		//查询总数
//		page.setTotalCount(countUserPageByActivityId(bean.getActivityId()));
		page.setTotalCount(scQuesionsDao.countListQuestions(bean.getActivityId()));
		return page;
	}*/
	
	public List<ScQuestionsBean> listQuestions(ScQuestionsBean bean) {
		//必填参数校验
		MyAssert.notNull(bean.getActivityId(), "参数[活动ID]为空");
		return scQuesionsDao.findByActivityId(bean.getActivityId());
	}
	
	/**
	 * 根据活动ID分页查询问题列表
	 * 在新页面显示
	 * 参数：活动id、用户id
	 */
	//分页查询的代码
	public Page<ScQuestionsBean> findQuestionsPage(ScQuestionsBean bean) {
		//必填参数校验
		//如果取得的活动Id为空，则抛出运行时异常
		MyAssert.notNull(bean.getActivityId(), "参数[活动ID]为空");
		//分页查询
		Page<ScQuestionsBean> page = new Page<ScQuestionsBean>();
		//CriteriaBuilder创建查询
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<ScQuestionsBean> cq = cb.createQuery(ScQuestionsBean.class);
		Root<ScQuestionsBean>  root = cq.from(ScQuestionsBean.class);
		//整合查询条件
		List<Predicate> pres = new ArrayList<Predicate>();
		pres.add(cb.equal(root.get("activityId"), bean.getActivityId()));
		//日期
		if(bean.getStartTime() != null) {
			pres.add(cb.greaterThanOrEqualTo(root.<Date>get("ctime"), bean.getStartTime()));
		}
		if(bean.getEndTime() != null) {
			pres.add(cb.lessThan(root.<Date>get("ctime"), DateUtils.addDay(bean.getEndTime(), 1)));
		}
		if(bean.getId()!=null) {
			pres.add(cb.equal(root.get("id"), bean.getId()));
		}
		Predicate p = cb.and(pres.toArray(new Predicate[pres.size()]));
		cq.where(p);//and
		cq.orderBy(cb.desc(root.get("id")));//排序
		//执行查询
		TypedQuery<ScQuestionsBean> query = entityManager.createQuery(cq);
		query.setFirstResult(bean.getStart());
		query.setMaxResults(bean.getPageSize());
		List<ScQuestionsBean> list = query.getResultList();
		//查询客户名称和活动名称
		if(list != null && list.size() > 0) {
			List<Long> userIds = new ArrayList<Long>(list.size());
			List<Long> acIds = new ArrayList<Long>(list.size());
			for(ScQuestionsBean b : list) {
				userIds.add(b.getCompanyUserId());
				acIds.add(b.getActivityId());
			}
			//根据用户ids查询用户
			List<ScUCompanyUserBean> users = companyUserDao.findUsersByIds(userIds);
			Map<Long, String> userMap = new HashMap<Long, String>();
			for(ScUCompanyUserBean user : users) {
				userMap.put(user.getId(), user.getUserName());
			}
			//根据活动ids查询活动名称
			List<ScActivityBean> activities = activityDao.findByIds(acIds);
			Map<Long, String> acMap = new HashMap<Long, String>();
			for(ScActivityBean activity : activities){
				acMap.put(activity.getId(), activity.getTopic());
			}
			
			for(ScQuestionsBean b : list) {
				if(userMap != null) {
					b.setUserName(userMap.get(b.getCompanyUserId()));
				}
				if(acMap != null) {
					b.setActivityTopic(acMap.get(b.getActivityId()));
				}
			}
		}
		
		page.setResultList(list);
		//查询总数
//		page.setTotalCount(countUserPageByActivityId(bean.getActivityId(),bean.getStartTime(),DateUtils.addDay(bean.getEndTime(), 1)));
		page.setTotalCount(scQuesionsDao.countQuestions(bean.getActivityId(),bean.getStartTime(),DateUtils.addDay(bean.getEndTime(), 1)));
		return page;
	}
	
	/**
	 * 根据活动ID查询客户总数
	 */
/*	public Integer countUserPageByActivityId(Long activityId,Date start,Date end) {
		String sql = "SELECT COUNT(ID) FROM SC_QUESTIONS T WHERE T.activity_Id=? and ctime >= ? and ctime < ?";
		Query query = entityManager.createNativeQuery(sql);
		query.setParameter(1, activityId);
		query.setParameter(2, start);
		query.setParameter(3, end);
		return Integer.parseInt(query.getSingleResult().toString());
	}
	*/
//	@Override
//	public Page<ScQuestionsBean> findByPage(Specification<ScQuestionsBean> spec,PageRequest pageRequest) {
//		return (Page<ScQuestionsBean>) scQuesionsDao.findAll(spec, pageRequest);
//	}
	
	@Override
	public ScQuestionsBean getQuestion(Long id) {
		return scQuesionsDao.findById(id);
	}
	
	public List<ScActivityBean> findActivitiesByArea(int managerType) {
		return scQuesionsDao.findActivitiesByArea(managerType);
	}
}
